#include <iostream>
#include "TcpServer.hpp"
#include <stdio.h>
#include "Protocal.hpp"
#include "LVProtocol.hpp"

// ./client 127.0.0.1 8080
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "PLEASE USAGE ./CLIENT IP PORT" << std::endl;
    }
    std::string sport = argv[2];
    int port = stoi(sport);

    std::string sip = argv[1];

    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);

    // 客户端的信息
    struct sockaddr_in server;
    socklen_t len = sizeof(server);
    memset(&server, 0, sizeof(server));

    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(sip.c_str());
    int n = connect(sockfd, CONV(&server), len);
    if (n != 0)
    {
        LOG(LogLevel::FATAL) << "connect server failed";
        Die(CONNECT_ERR);
    }

    LOG(LogLevel::INFO) << "connect success, sockfd is : " << sockfd;

    while (true)
    {
        int x, y;
        char oper;
        std::cout << "请输入x的值: ";
        std::cin >> x;

        std::cout << "请输入y的值: ";
        std::cin >> y;

        std::cout << "请输入oper的值: ";
        std::cin >> oper;

        // request req(x, y, oper);
        // std::string client_request;
        // req.Serialize(client_request); // 序列化
        // Encode(client_request);        // 添加报头
        std::string id = zj::UUID::uuid();
        std::cout << "id: " << id << std::endl;
        Json::Value parms;
        parms["X"] = x;
        parms["Y"] = y;
        parms["OPER"] = oper;

        std::shared_ptr<zj::NetCalRequest> msg = std::make_shared<zj::NetCalRequest>();
        msg->setparms(parms);
        msg->setId(id);
        msg->setMType(zj::MType::ADD_REQUEST);
        std::string client_request = zj::LVProtocol::Encode(msg);
        std::cout << "client_request: " << client_request << std::endl;

        int n = send(sockfd, client_request.c_str(), client_request.size(), 0);
        std::cout << "n: " << n << std::endl;
        std::cout << "client send成功" << std::endl;

        std::string client_response;

        // 长任务，一个线程处理一个客户端

        char buffer[4096];
        n = recv(sockfd, buffer, sizeof(buffer) - 1, 0);
        buffer[n] = 0;
        LOG(LogLevel::INFO) << buffer;

        // 现在是对收到的消息做处理，消息来源(我自己创建一个缓冲区用来存放从网络中读到的数据)
        client_response.append(buffer, n);
        std::string message; // 用于接收去除报头的报文
        std::shared_ptr<zj::BaseMessage> ptr = std::make_shared<zj::NetCalResponse>();
        std::cout << "client_response: " << client_response << std::endl;
        // 在handler内部，只有在packge>=一个报文长度时，才会进行处理，否则返回一个空串
        if (zj::LVProtocol::Decode(client_response, ptr))
        {
            std::cout << "client Decode成功" << std::endl;
            // message = "echo#: " + message;
            if (ptr->mtype() != zj::MType::ADD_RESPONSE)
            {
                std::cout << "服务器返回类型错误" << std::endl;
            }
            auto msg_ptr = std::dynamic_pointer_cast<zj::NetCalResponse>(ptr);
            if (msg_ptr->check())
            {
                std::cout << msg_ptr->result() << "[" << (int)msg_ptr->rcode() << "]" << std::endl;
            }
        }
    }
}
// ./client_tcp server_ip server_port
/*int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Usage:./client_tcp server_ip server_port" << std::endl;
        return 1;
    }
    std::string server_ip = argv[1]; // "192.168.1.1"
    int server_port = std::stoi(argv[2]);
    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cout << "create socket failed" << std::endl;
        return 2;
    }

    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(server_port);
    server_addr.sin_addr.s_addr = inet_addr(server_ip.c_str());

    // client 不需要显示的进行bind, tcp是面向连接的, connect 底层会自动进行bind
    int n = ::connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr));
    if (n < 0)
    {
        std::cout << "connect failed" << std::endl;
        return 3;
    }
    // echo client
    std::string message;
    while (true)
    {
        int x, y;
        char oper;
        std::cout << "input x: ";
        std::cin >> x;
        std::cout << "input y: ";
        std::cin >> y;
        std::cout << "input oper: ";
        std::cin >> oper;

        request req(x, y, oper);

        // 1. 序列化
        req.Serialize(message);

        // 2. Encode
        Encode(message);

        // 3. 发送
        n = ::send(sockfd, message.c_str(), message.size(), 0);
        if (n > 0)
        {
            char inbuffer[1024];
            // 4. 获得应答
            int m = ::recv(sockfd, inbuffer, sizeof(inbuffer), 0);
            if (m > 0)
            {
                inbuffer[m] = 0;
                std::string package = inbuffer;//TODO
                std::string content;
                // 4. 读到应答完整--暂定, decode
                Decode(package, &content);

                // 5. 反序列化
                response resp;
                resp.Deserialize(content);

                // 6. 得到结构化数据
                std::cout << resp.result() << "[" << resp.code() << "]" << std::endl;
            }
            else
                break;
        }
        else
            break;
    }

    ::close(sockfd);
    return 0;
}*/